//
// Created by lingwu on 2021/5/11.
//
#include "iostream"
#ifndef DEMO_BTREE_H
#define DEMO_BTREE_H

#endif //DEMO_BTREE_H
typedef char ElemType;
#define MaxSize 50
typedef struct node{
//    数据结点类型
    ElemType data;
    struct node *lchild;
    struct  node *rchild;
}BTNode;
void CreateBTree(BTNode *&b,char *str){
//    用括号表示法创建二叉树函数
    BTNode *St[MaxSize],*p;
    int top=-1,k,j=0;
    char ch;
    b=NULL;
    ch=str[j];
    while(ch!='\0'){
        switch (ch) {
            case '(':top++;St[top]=p;k=1;break;
            case ')':top--;break;
            case ',':k=2;break;
            default:p= (BTNode *)malloc(sizeof(BTNode));
            p->data=ch;
            p->lchild=p->rchild=NULL;
                if (b==NULL)
                    b=p;
                else{
                    switch (k) {
                        case 1:St[top]->lchild=p;break;
                        case 2:St[top]->rchild=p;break;

                    }
                }

        }
        j++;
        ch=str[j];
    }
}
void DestroyBTree(BTNode *&b){
//    销毁二叉树
    if (b!=NULL){
        DestroyBTree(b->lchild);
        DestroyBTree(b->rchild);
        free(b);
    }
}
void DisBTree(BTNode *b){
//    括号表示法：显示二叉树
    if (b!=NULL){
        printf("%c",b->data);
        if (b->rchild!=NULL||b->lchild!=NULL){
            printf("(");
            DisBTree(b->lchild);
            if (b->rchild!=NULL)
                printf(",");
            DisBTree(b->rchild);
            printf(")");
        }
    }
}
void createBTree(BTNode *&b,char *str){
//    使用先序递归建立二叉树
    static int n=0;//标记用于创建结点所用的字符下标
    if (*(str+n)==' '){
        n++;
        return;
    }
    b=(BTNode*) malloc(sizeof(BTNode));
    b->data=*(str+n);
    b->lchild=NULL;
    b->rchild=NULL;
    n++;

    createBTree(b->lchild,str);
    createBTree(b->rchild,str);
    return;

}
void disBTree(BTNode *b){
//用于显示先序法构建的二叉树
    {	if(b==NULL) printf(" ");
        else
        {	printf("%c",b->data);
            disBTree(b->lchild);
            disBTree(b->rchild);
        }
    }
}
int LeafNodes(BTNode *b){
//    递归求叶子结点的个数
    int num1,num2;
    if (b==NULL)
        return 0;
    else if(b->lchild==NULL&&b->rchild==NULL)
        return 1;
    else{
        num1= LeafNodes(b->lchild);
        num2= LeafNodes(b->rchild);
        return (num1+num2);
    }
}
void showLeafNodes(BTNode *b){
//用于显示叶子结点
    if (b==NULL)
        return ;
    else if(b->lchild==NULL&&b->rchild==NULL){
        printf(" %c",b->data);
        return ;}
    else{
        showLeafNodes(b->lchild);
         showLeafNodes(b->rchild);
        return ;
    }

}
